package cn.zj.logistics.controller;

import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import cn.zj.logistics.mo.MessageObject;
import cn.zj.logistics.pojo.Role;
import cn.zj.logistics.pojo.RoleExample;
import cn.zj.logistics.pojo.User;
import cn.zj.logistics.pojo.UserExample;
import cn.zj.logistics.pojo.UserExample.Criteria;
import cn.zj.logistics.service.RoleService;
import cn.zj.logistics.service.UserService;

@Controller
@RequestMapping("/admin")
public class AdminController {
	
	@Autowired
	private UserService userService;
	
	
	@Autowired
	private RoleService roleService;
	
	
	@RequestMapping("/login")
	public String login(HttpServletRequest request,Model m) {
		//org.apache.shiro.authc.UnknownAccountException
		//org.apache.shiro.authc.IncorrectCredentialsException
		//获取错误信息
		String shiroLoginFailure = (String) request.getAttribute("shiroLoginFailure");
		System.out.println("shiroLoginFailure :"+shiroLoginFailure);
		
		if(UnknownAccountException.class.getName().equals(shiroLoginFailure)) {
			m.addAttribute("errorMsg", "亲，账号不存在");
		}else if(IncorrectCredentialsException.class.getName().equals(shiroLoginFailure)) {
			m.addAttribute("errorMsg", "亲，密码错误");
		}
		
		return "forward:/login.jsp";
	}
	
	//页面跳转功能
	
	@RequiresPermissions("admin:adminPage")
	@RequestMapping("/adminPage")
	public String adminPage() {
		
		return "adminPage";
	}
	
	@RequestMapping("/adminEdit")
	public String adminEdit(Model m,Long userId) {
		
		//如果用户id不等于空，说明是修改操作，查询用户对象共享过去，以供回显
		if(userId !=null) {
			User user = userService.selectByPrimaryKey(userId);
			m.addAttribute("user", user);
		}
		
		//查询出所有的角色
		RoleExample example = new RoleExample();
		List<Role> roles = roleService.selectByExample(example );
		
		m.addAttribute("roles", roles);
		
		return "adminEdit";
	}
	
	@RequestMapping("/checkUsername")
	@ResponseBody
	public boolean checkUsername(String username) {
		
		UserExample example = new UserExample();
		Criteria criteria = example.createCriteria();
		criteria.andUsernameEqualTo(username);
		
		List<User> users = userService.selectByExample(example );
		
		return users.size() == 0 ? true:false;
	}
	
	
	//新增功能
	@RequestMapping("/insert")
	@RequiresPermissions("admin:insert")
	@ResponseBody
	public MessageObject insert(User user) {
		
		/*
		 * 密码加盐使用MD5散列三次存入数据库中
		 */
		//使用随机数取5位作为盐
		String salt = UUID.randomUUID().toString().substring(0, 5);
		Md5Hash md5Hash = new Md5Hash(user.getPassword(), salt, 3);
		user.setPassword(md5Hash.toString());
		
		user.setSalt(salt);
		
		
		//设置日期
		user.setCreateDate(new Date());
		
		MessageObject mo = MessageObject.createMessageObject(0, "新增数据失败，请联系管理员");
		
		int row = userService.insert(user);
		if(row == 1) {
			mo = MessageObject.createMessageObject(1, "新增数据成功");
		}
		
		return mo;
	}
	//修改功能
	@RequestMapping("/update")
	@RequiresPermissions("admin:update")
	@ResponseBody
	public MessageObject update(User user) {
		
		
		/*
		 * 密码加盐使用MD5散列三次存入数据库中
		 */
		//使用随机数取5位作为盐
		String salt = UUID.randomUUID().toString().substring(0, 5);
		Md5Hash md5Hash = new Md5Hash(user.getPassword(), salt, 3);
		user.setPassword(md5Hash.toString());
		user.setSalt(salt);
		
		
		MessageObject mo = MessageObject.createMessageObject(0, "修改数据失败，请联系管理员");
		
		int row = userService.updateByPrimaryKeySelective(user);
		if(row == 1) {
			mo = MessageObject.createMessageObject(1, "修改数据成功");
		}
		
		return mo;
	}
	
	
	//数据列表功能
	@ResponseBody
	@RequestMapping("/list")
	@RequiresPermissions("admin:list")
	public PageInfo<User> list(@RequestParam(defaultValue = "1") int pageNum,
				@RequestParam(defaultValue = "10") int pageSize,String keyword){
		
		PageHelper.startPage(pageNum, pageSize);
		
		UserExample example = new UserExample();
		
		//条件搜索查询
		
		if(StringUtils.isNotBlank(keyword)) {
			//userhname或者realname模糊查询
			
			Criteria criteria1 = example.createCriteria();
			criteria1.andUsernameLike("%"+keyword+"%");
			
			Criteria criteria2 = example.createCriteria();
			criteria2.andRealnameLike("%"+keyword+"%");
			
			//两个条件or关系
			example.or(criteria2);
			
		}
		List<User> users = userService.selectByExample(example);

		
		PageInfo<User> pageInfo = new PageInfo<User>(users);
		
		return pageInfo;
	}
	
	@RequestMapping("/delete")
	@RequiresPermissions("admin:delete")
	@ResponseBody
	public MessageObject delete(Long userId) {
		
		//创建消息对象
		MessageObject mo = MessageObject.createMessageObject(0, "删除数据失败，请联系管理员");
		
		int row = userService.deleteByPrimaryKey(userId);
		
		if(row == 1) {
			mo = MessageObject.createMessageObject(1, "删除数据成功");
		}
		return mo;
	}
	
	
}
